package com.learning.platform.repository;

import com.learning.platform.entity.QuestionBank;
import com.learning.platform.enums.Difficulty;
import com.learning.platform.enums.QuestionType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface QuestionBankRepository extends JpaRepository<QuestionBank, Long> {
    
    /**
     * 分页查询课程题库
     */
    @Query("SELECT q FROM QuestionBank q WHERE q.courseId = :courseId " +
           "AND (:questionType IS NULL OR q.questionType = :questionType) " +
           "AND (:difficulty IS NULL OR q.difficulty = :difficulty) " +
           "AND (:keyword IS NULL OR q.title LIKE %:keyword% OR q.content LIKE %:keyword%) " +
           "ORDER BY q.createdAt DESC")
    Page<QuestionBank> findByCourseId(@Param("courseId") Long courseId,
                                    @Param("questionType") QuestionType questionType,
                                    @Param("difficulty") Difficulty difficulty,
                                    @Param("keyword") String keyword,
                                    Pageable pageable);
    
    /**
     * 搜索题目（别名方法）
     */
    default Page<QuestionBank> searchQuestions(Long courseId, QuestionType questionType, String difficulty, String keyword, Pageable pageable) {
        // 将String difficulty转换为Difficulty枚举
        Difficulty difficultyEnum = null;
        if (difficulty != null && !difficulty.isEmpty()) {
            try {
                difficultyEnum = Difficulty.valueOf(difficulty.toUpperCase());
            } catch (IllegalArgumentException e) {
                // 忽略无效的难度值
            }
        }
        return findByCourseId(courseId, questionType, difficultyEnum, keyword, pageable);
    }
    
    /**
     * 查询课程下的所有题目
     */
    List<QuestionBank> findByCourseIdOrderByCreatedAtDesc(Long courseId);
    
    /**
     * 根据创建者查询题目
     */
    Page<QuestionBank> findByCreatedByOrderByCreatedAtDesc(Long createdBy, Pageable pageable);
    
    /**
     * 统计课程题目数量
     */
    long countByCourseId(Long courseId);
    
    /**
     * 按题型统计课程题目数量
     */
    @Query("SELECT q.questionType, COUNT(q) FROM QuestionBank q WHERE q.courseId = :courseId GROUP BY q.questionType")
    List<Object[]> countByCourseIdGroupByType(@Param("courseId") Long courseId);
    
    /**
     * 按难度统计课程题目数量
     */
    @Query("SELECT q.difficulty, COUNT(q) FROM QuestionBank q WHERE q.courseId = :courseId GROUP BY q.difficulty")
    List<Object[]> countByCourseIdGroupByDifficulty(@Param("courseId") Long courseId);
}